package com.usian.gateway.fliter;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class MyFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain ) {
        String loginPageIUrl = "user/login";

        log.info("执行网关");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        log.info("url是：{}",path);
        //知道当前的url是不是登陆的url
        //1：只有登陆的情况下，才能访问页面 2：访问页面的时候或者api.access_token(访问令牌)

        //鉴权（简单）
        if (path.contains(loginPageIUrl)||path.contains("/goHtml")||path.contains(".html")){
            log.info("本次是登陆页面 ， 直接放行");
            return chain.filter(exchange);
        }else {
            log.info("本次访问的不是登录页面，是其他页面");
            String token = getToken(request);
            //如果token没有值 ， 代表之前没有登陆过
            if (StringUtils.isBlank(token)){
                log.info("重定向到登录页面");
                //状态 ：没有权限  401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }else {
                try {


//                    boolean i = JWTUtil.verify(token, "user".getBytes());
                    boolean verify = JWTUtil.verify(token, "123".getBytes());
                    if (verify){
                    log.info("放行");
                        return chain.filter(exchange);
                    }else {
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        return response.setComplete();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            }

        }
    }

    @Override
    public int getOrder() {
        return 1;
    }

    public String getToken(ServerHttpRequest request){
        String token = request.getHeaders().getFirst("token");
        log.info("token:{}",token);
        return token;
    }
}
